//
//  STOrientationController.swift
//  iPhone
//
//  Created by Toj on 5/15/23.
//

/**
 * NOTE:
 * 不推荐: 使用通知监听屏幕旋转, iOS16以后通知失效, 而且可能接收到多次通知
 * 建议: 使用viewWillTransition用size去判断横竖屏,
 * 获取方向 uiapplication.shared.app_or....
 * 如果默认竖屏高度是可变的建议再2次赋值更改UI 判断是否是横屏, 横屏更新竖屏高度值不做frame设置, 这样不影响当前横屏状态.
 * 如果改变横屏高度建议判断是否是竖屏状态同上
 */

import UIKit

// MARK: - 懒加载(属性), 变量, 初始化init
class STOrientationController: STBaseViewController {
    
    /* 切换 */
    private lazy var switchButton: UIButton = {
        let view = UIButton()
        view.titleLabel?.font = 14.to_boldFont(name: .roboto)
        view.backgroundColor = .random
        view.setTitleColor(.random, for: .normal)
        view.setTitle("横屏", for: .normal)
        view.setTitle("竖屏屏", for: .selected)
        view.addTarget(self, action: #selector(didTapSwitch(sender:)), for: .touchUpInside)
        return view
    }()
    
    /* 跳转 */
    private lazy var presentButton: UIButton = {
        let view = UIButton()
        view.backgroundColor = .random
        view.setTitleColor(.random, for: .normal)
        view.setTitle("跳转", for: .normal)
        view.addTarget(self, action: #selector(didTapPresent(sender:)), for: .touchUpInside)
        return view
    }()
    
    /* 暂停 */
    private lazy var lockButton: UIButton = {
        let view = UIButton()
        view.backgroundColor = .random
        view.setTitleColor(.random, for: .normal)
        view.setTitle("锁定", for: .normal)
        view.setTitle("解锁", for: .selected)
        view.addTarget(self, action: #selector(didTapLock(sender:)), for: .touchUpInside)
        return view
    }()
    
    var _supportedRotation = true
    var supportedRotation: Bool {
        set {
            guard newValue != _supportedRotation else { return }
            if !newValue {
                UIApplication.shared.app_setOrientationLandscape(viewController: self)
            }
            _supportedRotation = newValue
            
            guard #available(iOS 16.0, *) else {
                UIViewController.attemptRotationToDeviceOrientation()
                return
            }
            navigationController?.setNeedsUpdateOfSupportedInterfaceOrientations()
            setNeedsUpdateOfSupportedInterfaceOrientations()
        }
        get {
            _supportedRotation
        }
        
    }
    
    func reloadSupportedRotation() {
        supportedRotation = !(isShowAd || isShowAlert)
    }
    
    var isShowAd = false
    var isShowAlert = false
    
    // 当前方向
    private lazy var currentOrientation: UIInterfaceOrientation = UIApplication.shared.app_orientation
    { didSet {
        print("-->toj: currentOrientation: \(currentOrientation)")
    } }
    
    // 之前方向
    private lazy var beforOrientation: UIInterfaceOrientation = currentOrientation
}

// MARK: - 生命周期
extension STOrientationController {
    
    override var shouldAutorotate: Bool {
        print("-->toj: or func: \(#function)")
        return true
    }
    
    override var supportedInterfaceOrientations: UIInterfaceOrientationMask {
        let orientation = UIApplication.shared.app_orientation
        print("-->toj: or func: \(#function), orientation: \(orientation.rawValue)")
        return supportedRotation ? .allButUpsideDown : .portrait
    }
    
    override var preferredInterfaceOrientationForPresentation: UIInterfaceOrientation {
        print("-->toj: or func: \(#function), preferred: \(currentOrientation.rawValue)")
        return .portrait
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        setupMakeInitialize()
        setupMakeAddSubviews()
        setupMakeLayoutSubviews()
    }
    
    override func viewWillTransition(to size: CGSize,
                                     with coordinator: UIViewControllerTransitionCoordinator) {
        print("-->toj: or func: \(#function), size:\(size)")
    }
    
    
    override func viewDidDisappear(_ animated: Bool) {
        super.viewDidDisappear(animated)
        UIApplication.shared.app_setOrientationPortrait(viewController: self)
    }
}

// MARK: - 点击事件
@objc private extension STOrientationController {
    
    func didTapBack(sender: Any) {
        let orientation = UIApplication.shared.app_orientation
        if orientation.isLandscape {
            UIApplication.shared.app_setOrientationPortrait(viewController: self)
            return
        }
        navigationController?.popViewController(animated: true)
    }
    
    
    func didTapLock(sender: UIButton) {
        
        sender.isSelected = !sender.isSelected
        isShowAlert = sender.isSelected
//        reloadSupportedRotation()
    }
    
    func didTapSwitch(sender: UIButton) {
        sender.isSelected = !sender.isSelected
        
        let isSelected = sender.isSelected
        
        let orientation: UIInterfaceOrientationMask = isSelected ? .landscape : .portrait
        UIApplication.shared.app_setOrientation(interfaceMask: orientation, viewController: self)
    }

    func didTapPresent(sender: UIButton) {
        sender.isSelected = !sender.isSelected
        isShowAd = sender.isSelected
        // reloadSupportedRotation()
        let random = arc4random_uniform(2)
        UIApplication.shared.app_setOrientation(interfaceMask: .portrait, viewController: self)
        if random == 0 {
            beforOrientation = UIApplication.shared.app_orientation
            let vc = STFullScreenAdController()
            navigationController?.pushViewController(vc, animated: true)
            return
        }
        let vc = STFullScreenAdController()
        vc.fromViewController = self
        vc.modalPresentationStyle = .overFullScreen
        present(vc, animated: true)
    }
}

// MARK: - 初始化设置
private extension STOrientationController {
    
    func setupMakeAddSubviews() {
        view.addSubview(presentButton)
        view.addSubview(switchButton)
        view.addSubview(lockButton)
    }
    
    func setupMakeLayoutSubviews() {
        switchButton.snp.makeConstraints { make in
            make.centerY.equalTo(view)
            make.left.equalTo(50)
            make.width.equalTo(120)
            make.height.equalTo(44)
        }
        
        presentButton.snp.makeConstraints { make in
            make.centerY.equalTo(view)
            make.left.equalTo(200)
            make.width.equalTo(120)
            make.height.equalTo(44)
        }
        
        lockButton.snp.makeConstraints { make in
            make.centerX.equalTo(view)
            make.top.equalTo(120)
            make.width.equalTo(120)
            make.height.equalTo(44)
        }
    }
    
    func setupMakeInitialize() {
        view.backgroundColor = .random
        // reloadSupportedRotation()
    }
}
